<template>
  <el-breadcrumb separator="/">
    <el-breadcrumb-item>{{ $t('Home') }}</el-breadcrumb-item>
    <el-breadcrumb-item>{{ $t('BlockChain') }}</el-breadcrumb-item>
    <el-breadcrumb-item>{{ $t('APITest') }}</el-breadcrumb-item>
  </el-breadcrumb>
  <el-row class="test-container">
    <el-col :span="5">
      <div class="menu-wrapper">
        <h3 class="menu-title">{{ $t('API Methods') }}</h3>
        <el-menu class="menu-with-flex">
          <el-menu-item v-for="item in menuList" :key="item.method_name" @click="handleClick(item)" :class="{ 'selected-item': item.selected }">
            <el-tag :type="item.method_type === 'invoke' ? 'success' : 'primary'" class="method-tag">
              {{ item.method_name }}
            </el-tag>
          </el-menu-item>
        </el-menu>
      </div>
    </el-col>
    <el-col :span="6" class="params-section">
      <div class="params-wrapper" v-if="selectedItem">
        <h3 class="section-title">{{ $t('Parameters') }}</h3>
        <el-descriptions :column="1" border>
          <el-descriptions-item v-for="param in selectedItem.parameters" :key="param.name" :label="param.label">
            <el-input v-model="param.value" :placeholder="param.label" class="param-input">
            </el-input>
          </el-descriptions-item>
        </el-descriptions>
        <div class="button-wrapper">
          <el-button type="primary" @click="test()">{{ $t('send') }}</el-button>
        </div>
      </div>
    </el-col>
    <el-col :span="13" class="result-section">
      <div class="result-wrapper">
        <h3 class="section-title">{{ $t('Raw Result') }}</h3>
        <el-input
          type="textarea"
          v-model="response_json"
          :rows="8"
          readonly
        />
        
        <h3 class="section-title">{{ $t('Contract Result') }}</h3>
        <el-input
          type="textarea"
          v-model="result_json"
          :rows="8"
          readonly
        />
      </div>
    </el-col>
  </el-row>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import ApiClient from '@/api/ApiClient';
import { ApiRequest, ApiRequestBody } from '@/api/ApiRequest';
import { ApiResponse } from '@/api/ApiResponse';
import { config } from '@/config/config';

interface MenuItem {
  method_name: string;
  method_type: string;
  parameters: Parameter[];
  selected?: boolean;
}

interface Parameter {
  name: string;
  label: string;
  regex: string | null;
  value?: string; // 添加value属性用于表单输入
}

export default defineComponent({
  setup() {
    const { t } = useI18n();
    const menuList = ref<MenuItem[]>([]);
    const selectedItem = ref<MenuItem | null>(null);
    const response_json = ref<string>('');
    const result_json = ref<string>('');

    const fetchAndUpdateMenu = () => {
      const request = new ApiRequest(
        "query",
        config.dao_chain_name,
        new ApiRequestBody(
          config.dao_contract_name,
          "describe",
          {}
        )
      );
      ApiClient.sendSync(request, (response: ApiResponse) => {
        if(response.data.code_value as unknown as number == 0){
          const contractResult = response.data.contract_result as { [key: string]: string };
          menuList.value = JSON.parse(contractResult.result);
        }else{
          ElMessage.error(response.data.code);
        }
      });


    };

    onMounted(() => {
      fetchAndUpdateMenu();
    });

    const handleClick = (item: MenuItem) => {
      selectedItem.value = item;
      response_json.value = ''; // 清空结果显示
      result_json.value = '';
      menuList.value.forEach((menuItem) => {
        menuItem.selected = false;
      });
      item.selected = true;

      // 从本地存储中读取参数值
      if (item.parameters.length > 0) {
        item.parameters.forEach((param) => {
          const storedValue = localStorage.getItem(`param_${item.method_name}_${param.name}`);
          if (storedValue) {
            param.value = storedValue;
          }
        });
      }
    };

    const test = () => {
      if (!selectedItem.value) {
        return;
      }

      const methodName = selectedItem.value.method_name;
      const methodType = selectedItem.value.method_type;

      // 构建参数对象
      const params: { [key: string]: string } = {};
      selectedItem.value.parameters.forEach((param) => {
        if (typeof param.name === 'string' && typeof param.value === 'string') {
          params[param.name] = param.value;

          // 将参数值存储到本地存储
          localStorage.setItem(`param_${methodName}_${param.name}`, param.value);
        }
      });

      const request = new ApiRequest(
        methodType,
        config.dao_chain_name,
        new ApiRequestBody(
          config.dao_contract_name,
          methodName,
          params
        )
      );
      ApiClient.sendSync(request, (response: ApiResponse) => {
        response_json.value = JSON.stringify(response.data, null, 4);
        var r = response.data.contract_result as { [key: string]: string };
        try {
          result_json.value = JSON.stringify(JSON.parse(r.result), null, 4);
        }catch(e){
          result_json.value = r.result;
        }
      });
    }

    return {
      menuList,
      selectedItem,
      response_json,
      result_json,
      handleClick,
      test,
      t
    };
  }
});
</script>

<style scoped>
.test-container {
  margin: 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: calc(100vh - 200px);
  display: flex;
}

.el-col {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.menu-wrapper {
  padding: 16px;
  border-right: 1px solid #e6e6e6;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.menu-with-flex {
  flex: 1;
  overflow-y: auto;
  border-right: none;
  max-height: calc(100vh - 280px);
}

.menu-title,
.section-title {
  margin-bottom: 16px;
  color: #303133;
  font-size: 16px;
  font-weight: 500;
}

.method-tag {
  width: 100%;
  text-align: center;
  height: 24px;
  line-height: 24px;
}

.selected-item {
  background-color: #ecf5ff !important;
  border-radius: 4px;
}

.params-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.params-section {
  padding: 16px;
  border-right: 1px solid #e6e6e6;
  height: 100%;
}

.el-descriptions {
  flex: 1;
  overflow-y: auto;
}

.param-input {
  margin-bottom: 8px;
}

.button-wrapper {
  margin-top: 24px;
  text-align: right;
}

.result-section {
  padding: 16px;
  height: 100%;
}

.result-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
}

::-webkit-scrollbar {
  width: 6px;
  height: 6px;
  background-color: #f5f7fa;
}

::-webkit-scrollbar-thumb {
  border-radius: 3px;
  background-color: #909399;
}

::-webkit-scrollbar-thumb:hover {
  background-color: #606266;
}

.el-menu-item {
  height: 40px;
  line-height: 40px;
}
</style>